//
//  HZOauthViewController.swift
//  555wobo
//
//  Created by 黄某某 on 15/12/19.
//  Copyright © 2015年 黄某某. All rights reserved.
//

import UIKit

import SVProgressHUD

class HZOauthViewController: UIViewController , UIWebViewDelegate{
    override func loadView() {
        view = webView
        webView.delegate = self
    }
    func webViewDidStartLoad(webView: UIWebView) {
        SVProgressHUD.showWithStatus("正在加载", maskType: SVProgressHUDMaskType.Black)
    }
    func webViewDidFinishLoad(webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
    override func viewDidLoad() {
        super.viewDidLoad()
        let url = HZNetworking.sharedInstance.oAuthURL()
        let request = NSURLRequest(URL: url)
        webView.loadRequest(request)
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "填充", style: UIBarButtonItemStyle.Plain, target: self, action: "autoFill")
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "取消", style: UIBarButtonItemStyle.Plain, target: self, action: "close")
        navigationItem.title = "登陆"

    }
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        let url = request.URL!.absoluteString
        print("url： \(url)")
        if !url.hasPrefix(HZNetworking.sharedInstance.redirect_uri) {
            return true
        }
        if let query = request.URL?.query {
            let codeString = "code="
            if query.hasPrefix(codeString) {
                let queryNS = query as NSString
                let code = queryNS.substringFromIndex(codeString.characters.count)
                print("code = \(code)")
                loadAccessToken(code)
            } else {
                self.close()
            }
        } else {
            print("query没有值")
        }
        
        
        return false
    }
    func loadAccessToken(code:String){
        HZNetworking.sharedInstance.loadAccessToken(code){ (result, error) -> () in
            if error != nil && result == nil {
                print("error: \(error)")
                SVProgressHUD.showInfoWithStatus("您的网络不给力")
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (Int64)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), { () -> Void in
                    self.close()
                })
                return
            }
            print("result: \(result)")
            let userAuccount = HZUserAccount(dict: result!)
            userAuccount.saveUserAccount()
            print("userAccount:\(userAuccount)")
            (UIApplication.sharedApplication().delegate as! AppDelegate).switchRootViewController(false)
        }
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()

    }
    func autoFill(){
        let js = "document.getElementById('userId').value='18822875184'; document.getElementById('passwd').value='15915808070';"
        webView.stringByEvaluatingJavaScriptFromString(js)
        
    }
    func close(){
        SVProgressHUD.dismiss()
        dismissViewControllerAnimated(true, completion: nil)
    }
    private lazy var webView = UIWebView()

}
